/*
 *  Copyright (C) 1998-2020 by Northwoods Software Corporation. All Rights Reserved.
 */

import * as go from 'gojs';
import { ReactPalette } from 'gojs-react';
import * as React from 'react';
import linkImg from '../../assets/link.svg';
// 组件图标icon
import attentionIcon from '../../assets/icons/attention.svg';
import collectIcon from '../../assets/icons/collect.svg';
import conditionIcon from '../../assets/icons/condition.svg';
import endIcon from '../../assets/icons/end.svg';
import interfaceIcon from '../../assets/icons/interface.svg';
import personIcon from '../../assets/icons/person.svg';
import presskeyIcon from '../../assets/icons/presskey.svg';
import skipIcon from '../../assets/icons/skip.svg';

const $ = go.GraphObject.make;
const iconMargin = new go.Margin(0, 4, 0, 0);
const btnMargin = new go.Margin(0, 4, 0, 0);

interface PaletteProps {
  nodeDataArray: Array<go.ObjectData>;
  linkDataArray?: Array<go.ObjectData>;
  modelData?: go.ObjectData;
}

// function animateFadeDown(e: any) {
//   var diagram = e.diagram;
//   var animation = new go.Animation();
//   animation.isViewportUnconstrained = true; // So Diagram positioning rules let the animation start off-screen
//   animation.easing = go.Animation.EaseOutExpo;
//   animation.duration = 900;
//   // Fade "down", in other words, fade in from above
//   animation.add(
//     diagram,
//     "position",
//     diagram.position.copy().offset(0, 200),
//     diagram.position
//   );
//   animation.add(diagram, "opacity", 0, 1);
//   animation.start();
// }

/**
 * 顶部diagram组件集dom容器
 * 示例：AI管理-机器人管理-版本管理-配置话术流程
 */
export class PaletteWrapper extends React.Component<PaletteProps, {}> {
  /**
   * Ref to keep a reference to the Diagram component, which provides access to the GoJS diagram via getDiagram().
   */
  private paletteRef: React.RefObject<ReactPalette>;

  /** @internal */
  constructor(props: PaletteProps) {
    super(props);
    console.log('流程配置-面板初始化:', props);
    this.paletteRef = React.createRef();
  }

  /**
   * Get the diagram reference and add any desired diagram listeners.
   * Typically the same function will be used for each listener, with the function using a switch statement to handle the events.
   */
  // public componentDidMount() {
  //   if (!this.paletteRef.current) return;
  //   const diagram = this.paletteRef.current.getDiagram();
  //   if (diagram instanceof go.Diagram) {
  //     diagram.addDiagramListener('ChangedSelection', this.props.onDiagramEvent);
  //   }
  // }

  /**
   * Get the diagram reference and remove listeners that were added during mounting.
   */
  // public componentWillUnmount() {
  //   if (!this.diagramRef.current) return;
  //   const diagram = this.diagramRef.current.getDiagram();
  //   if (diagram instanceof go.Diagram) {
  //     diagram.removeDiagramListener('ChangedSelection', this.props.onDiagramEvent);
  //   }
  // }

  /**
   * Diagram initialization method, which is passed to the ReactDiagram component.
   * This method is responsible for making the diagram and initializing the model, any templates,
   * and maybe doing other initialization tasks like customizing tools.
   * The model's data should not be set here, as the ReactDiagram component handles that.
   */
  private initPalette(): go.Palette {
    const myPalette = $(go.Palette, {
      //用Gridlayout格子布局垂直排列每行数据
      contentAlignment: go.Spot.TopLeft,
      // layout: $(go.GridLayout, {
      //   alignment: go.GridLayout.LeftToRight,
      // }),
      // isReadOnly: true, // 禁止编辑
      // maxSelectionCount: 1,
      // "animationManager.initialAnimationStyle": go.AnimationManager.None,
      // InitialAnimationStarting: animateFadeDown,
      hasVerticalScrollbar: false,
      hasHorizontalScrollbar: false,
    });
    /**
     * 组件icon转换
     */
    function theIconFlagConverter(icon: any) {
      // console.log(icon, "图标名称");
      let path = '';
      switch (icon) {
        case 'attention':
          path = attentionIcon;
          break;
        case 'collect':
          path = collectIcon;
          break;
        case 'condition':
          path = conditionIcon;
          break;
        case 'end':
          path = endIcon;
          break;
        case 'interface':
          path = interfaceIcon;
          break;
        case 'person':
          path = personIcon;
          break;
        case 'presskey':
          path = presskeyIcon;
          break;
        case 'skip':
          path = skipIcon;
          break;
        default:
          path = linkImg;
      }
      return path;
    }
    myPalette.nodeTemplate = $(
      go.Node,
      'Auto',
      {
        locationObjectName: 'TB',
        locationSpot: go.Spot.Left,
      },
      // 组件-按钮-样式
      $(
        go.Shape,
        {
          //fill: "#000",
          figure: 'RoundedRectangle',
          stroke: '#3393ff',
          strokeWidth: 0,
          margin: btnMargin,
          width: 115,
          height: 29,
        },
        new go.Binding('fill', 'fillcolor')
        //new go.Binding("parameter1", "p1"),
      ),
      // 容器
      $(
        go.Panel,
        'Horizontal',
        {
          alignment: go.Spot.Left,
          // margin: 5,
        },

        // icon图标
        $(
          go.Picture,
          {
            margin: iconMargin,
            width: 25,
            height: 25,
            source: linkImg, // icon图片
            //initialContentAlignment: go.Spot.Left
          },
          new go.Binding('source', 'icon', theIconFlagConverter),
          new go.Binding('visible', 'icon', function (nat) {
            return nat !== undefined;
          })
        ),
        // 文本
        $(
          go.TextBlock,
          {
            name: 'TB',
            textAlign: 'left',
            font: '12px helvetica, arial, sans-serif',
            stroke: '#fff',
            editable: true,
          },
          new go.Binding('text', 'title')
        )
      )
    );

    return myPalette;

    // const $ = go.GraphObject.make;
    // // set your license key here before creating the diagram: go.Diagram.licenseKey = "...";
    // const myPalette = $(go.Palette, {
    //   //用Gridlayout格子布局垂直排列每行数据
    //   layout: $(go.GridLayout, { alignment: go.GridLayout.Location }),
    //   model: $(go.GraphLinksModel, {
    //     linkKeyProperty: "key", // IMPORTANT! must be defined for merges and data sync when using GraphLinksModel
    //     // positive keys for nodes
    //     makeUniqueKeyFunction: (m: go.Model, data: any) => {
    //       let k = data.key || 1;
    //       while (m.findNodeDataForKey(k)) k++;
    //       data.key = k;
    //       return k;
    //     },
    //     // negative keys for links
    //     makeUniqueLinkKeyFunction: (m: go.GraphLinksModel, data: any) => {
    //       let k = data.key || -1;
    //       while (m.findLinkDataForKey(k)) k--;
    //       data.key = k;
    //       return k;
    //     },
    //   }),
    // });

    // // define a simple Node template
    // myPalette.nodeTemplate = $(
    //   go.Node,
    //   "Vertical",
    //   { locationObjectName: "TB", locationSpot: go.Spot.Center },
    //   $(
    //     go.Shape,
    //     { width: 20, height: 20, fill: "white" },
    //     new go.Binding("fill", "color")
    //   ),
    //   $(go.TextBlock, { name: "TB" }, new go.Binding("text", "color"))
    // );

    // return myPalette;
  }

  public render() {
    return (
      <ReactPalette
        ref={this.paletteRef}
        divClassName="palette-component"
        initPalette={this.initPalette}
        nodeDataArray={this.props.nodeDataArray}
        linkDataArray={this.props.linkDataArray}
        modelData={this.props.modelData}
      />
    );
  }
}
